package iputil.service;

import iputil.properties.IpProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class IpCountService {
    private Map<String,Integer> countMap = new HashMap<>();
    @Autowired
    private HttpServletRequest httpServletRequest ;
    public void count(){
        String remoteAddr = httpServletRequest.getRemoteAddr();
        System.out.println("-----------------"+remoteAddr);
        countMap.merge(remoteAddr, 1, Integer::sum);
    }
    @Autowired
    private IpProperties ipProperties;
    @Scheduled(cron = "0/#{ipProperties.cycle} * * * * ?")
    public void printCount(){
        if (ipProperties.getModel().equals(IpProperties.LogModel.DETAIL.getValue())){
            System.out.println("============================");
            for (Map.Entry<String, Integer> stringIntegerEntry : countMap.entrySet()) {
                System.out.println(stringIntegerEntry.getKey()+"-------->"+stringIntegerEntry.getValue());
            }
            System.out.println("============================");
            if (ipProperties.getCycleReset()){
                countMap.clear();
            }

        }else if (ipProperties.getModel().equals(IpProperties.LogModel.SIMPLE.getValue())){
            System.out.println("============================");
            for (Map.Entry<String, Integer> stringIntegerEntry : countMap.entrySet()) {
                System.out.println("ip:"+stringIntegerEntry.getKey());
            }
            System.out.println("============================");
        }


        if (ipProperties.getCycleReset()){
            countMap.clear();
        }
    }

    public static void main(String[] args) {
        new IpCountService().printCount();
    }
}
